<template>
  <div class="user-management-container">
    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-header">
        <h2>用户管理</h2>
        <div class="search-actions">
          <button class="btn btn-primary" @click="showAddModal">
            <i class="icon-add"></i> 添加用户
          </button>
        </div>
      </div>

      <div class="search-filters">
        <div class="filter-group">
          <label>用户名</label>
          <input
              v-model="searchParams.userName"
              type="text"
              placeholder="输入用户名搜索"
              class="filter-input"
          >
        </div>

        <div class="filter-group">
          <label>用户角色</label>
          <select v-model="searchParams.userRole" class="filter-select">
            <option value="">全部角色</option>
            <option value="user">普通用户</option>
            <option value="admin">管理员</option>
            <option value="ban">已封禁</option>
          </select>
        </div>

        <button class="btn btn-search" @click="doSubmit">
          <i class="icon-search"></i> 搜索
        </button>
      </div>
    </div>

    <!-- 用户表格 -->
    <div class="user-table-container">
      <div class="table-responsive">
        <table class="user-table">
          <thead>
          <tr>
            <th>头像</th>
            <th>用户名</th>
            <th>账号</th>
            <th>状态</th>
            <th>简介</th>
            <th>创建时间</th>
            <th>更新时间</th>
            <th>操作</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="record in dataList" :key="record.id">
            <td>
              <div class="user-avatar">
                <img
                    v-if="record.userAvatar"
                    :src="record.userAvatar"
                    :alt="record.userName"
                >
                <span v-else class="avatar-fallback">
                    {{ record.userName?.charAt(0) }}
                  </span>
              </div>
            </td>
            <td>{{ record.userName }}</td>
            <td>{{ record.userAccount }}</td>
            <td>
                <span class="role-badge" :class="'role-' + record.userRole">
                  {{ getUserRoleText(record.userRole) }}
                </span>
            </td>
            <td class="user-profile">
              <div class="profile-text" :title="record.userProfile">
                {{ record.userProfile }}
              </div>
            </td>
            <td>{{ moment(record.createTime).format("YYYY-MM-DD HH:mm") }}</td>
            <td>{{ moment(record.updateTime).format("YYYY-MM-DD HH:mm") }}</td>
            <td>
              <div class="action-buttons">
                <button class="btn-action btn-edit" @click="showEditModal(record)">
                  <i class="icon-edit"></i>
                </button>
                <button
                    v-if="record.userRole !== 'ban' && record.userRole !== 'admin'"
                    class="btn-action btn-ban"
                    @click="handleBanUser(record)"
                    title="封禁"
                >
                  <i class="icon-ban"></i>
                </button>
                <button
                    v-if="record.userRole === 'ban'"
                    class="btn-action btn-unban"
                    @click="handleUnbanUser(record)"
                    title="解封"
                >
                  <i class="icon-unban"></i>
                </button>
                <button
                    class="btn-action btn-delete"
                    @click="handleDelete(record)"
                    :disabled="record.userRole === 'admin'"
                    title="删除"
                >
                  <i class="icon-delete"></i>
                </button>
              </div>
            </td>
          </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页控件 -->
      <div class="pagination">
        <button
            class="pagination-btn"
            :disabled="searchParams.current === 1"
            @click="onPageChange(searchParams.current - 1)"
        >
          上一页
        </button>

        <span class="pagination-info">
          第 {{ searchParams.current }} 页 / 共 {{ Math.ceil(total / searchParams.pageSize) }} 页
        </span>

        <button
            class="pagination-btn"
            :disabled="searchParams.current * searchParams.pageSize >= total"
            @click="onPageChange(searchParams.current + 1)"
        >
          下一页
        </button>

        <select
            v-model="searchParams.pageSize"
            class="page-size-select"
            @change="doSubmit"
        >
          <option value="10">每页 10 条</option>
          <option value="20">每页 20 条</option>
          <option value="50">每页 50 条</option>
        </select>
      </div>
    </div>

    <!-- 添加用户模态框 -->
    <div class="modal-overlay" v-if="addModalVisible">
      <div class="modal-container">
        <div class="modal-header">
          <h3>添加用户</h3>
          <button class="modal-close" @click="addModalVisible = false">
            &times;
          </button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>用户名 <span class="required">*</span></label>
            <input v-model="addForm.userName" type="text" class="form-input">
          </div>
          <div class="form-group">
            <label>账号 <span class="required">*</span></label>
            <input v-model="addForm.userAccount" type="text" class="form-input">
          </div>
          <div class="form-group">
            <label>密码 <span class="required">*</span></label>
            <input
                v-model="addForm.userPassword"
                type="password"
                class="form-input"
            >
          </div>
          <div class="form-group">
            <label>角色</label>
            <select v-model="addForm.userRole" class="form-select">
              <option value="user">普通用户</option>
              <option value="admin">管理员</option>
            </select>
          </div>
          <div class="form-group">
            <label>用户简介</label>
            <textarea
                v-model="addForm.userProfile"
                class="form-textarea"
                rows="3"
            ></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-cancel" @click="resetAddForm">取消</button>
          <button class="btn btn-confirm" @click="handleAdd">确认添加</button>
        </div>
      </div>
    </div>

    <!-- 编辑用户模态框 -->
    <div class="modal-overlay" v-if="editModalVisible">
      <div class="modal-container">
        <div class="modal-header">
          <h3>编辑用户</h3>
          <button class="modal-close" @click="editModalVisible = false">
            &times;
          </button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>用户名</label>
            <input v-model="editForm.userName" type="text" class="form-input">
          </div>
          <div class="form-group">
            <label>头像URL</label>
            <input v-model="editForm.userAvatar" type="text" class="form-input">
            <div class="avatar-preview" v-if="editForm.userAvatar">
              <img :src="editForm.userAvatar" alt="头像预览">
            </div>
          </div>
          <div class="form-group">
            <label>用户简介</label>
            <textarea
                v-model="editForm.userProfile"
                class="form-textarea"
                rows="3"
            ></textarea>
          </div>
          <div class="form-group" v-if="editForm.id !== currentUser?.id">
            <label>角色</label>
            <select v-model="editForm.userRole" class="form-select">
              <option value="user">普通用户</option>
              <option value="admin">管理员</option>
              <option value="ban">封禁用户</option>
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-cancel" @click="resetEditForm">取消</button>
          <button class="btn btn-confirm" @click="handleEdit">保存更改</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref, watchEffect} from "vue";
import {
  User,
  UserControllerService,
  UserQueryRequest,
  UserAddRequest,
  UserUpdateRequest,
  DeleteRequest,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import moment from "moment";

const dataList = ref<User[]>([]);
const total = ref(0);
const searchParams = ref<UserQueryRequest>({
  userName: undefined,
  userRole: undefined,
  pageSize: 10,
  current: 1,
});

// 当前登录用户信息
const currentUser = ref<User | null>(null);

// 添加用户相关
const addModalVisible = ref(false);
const addForm = ref<UserAddRequest>({
  userName: '',
  userAccount: '',
  userPassword: '',
  userRole: 'user',
  userProfile: '',
});

// 编辑用户相关
const editModalVisible = ref(false);
const editForm = ref<UserUpdateRequest>({
  id: 0,
  userName: '',
  userAvatar: '',
  userProfile: '',
  userRole: 'user',
});

const loadData = async () => {
  try {
    const res = await UserControllerService.listUserByPageUsingPost(
        searchParams.value
    );
    if (res.code === 0) {
      dataList.value = res.data.records;
      total.value = res.data.total;
    } else {
      message.error("加载失败，" + res.message);
    }
  } catch (e) {
    message.error("加载用户数据失败");
  }
};

// 获取当前登录用户信息
const getCurrentUser = async () => {
  try {
    const res = await UserControllerService.getLoginUserUsingGet();
    if (res.code === 0) {
      currentUser.value = res.data;
    }
  } catch (e) {
    console.error("获取当前用户信息失败", e);
  }
};

/**
 * 监听 searchParams 变量，改变时触发页面的重新加载
 */
watchEffect(() => {
  loadData();
});

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
  getCurrentUser();
});

// 角色映射
const USER_ROLE_MAP = {
  user: "普通用户",
  admin: "管理员",
  ban: "已封禁",
} as const;

// 获取角色文本的方法
const getUserRoleText = (role: string) => {
  return USER_ROLE_MAP[role as keyof typeof USER_ROLE_MAP] || "未知状态";
};

const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

/**
 * 确认搜索，重新加载数据
 */
const doSubmit = () => {
  searchParams.value = {
    ...searchParams.value,
    current: 1,
  };
};

// 显示添加用户模态框
const showAddModal = () => {
  addModalVisible.value = true;
};

// 重置添加表单
const resetAddForm = () => {
  addForm.value = {
    userName: '',
    userAccount: '',
    userPassword: '',
    userRole: 'user',
    userProfile: '',
  };
  addModalVisible.value = false;
};

// 处理添加用户
const handleAdd = async () => {
  if (!addForm.value.userName || !addForm.value.userAccount || !addForm.value.userPassword) {
    message.error("请填写完整信息");
    return;
  }

  try {
    const res = await UserControllerService.addUserUsingPost(addForm.value);
    if (res.code === 0) {
      message.success("添加用户成功");
      addModalVisible.value = false;
      loadData();
      resetAddForm();
    } else {
      message.error("添加用户失败: " + res.message);
    }
  } catch (e) {
    message.error("添加用户失败");
    console.error(e);
  }
};

// 显示编辑用户模态框
const showEditModal = (record: User) => {
  editForm.value = {
    id: record.id,
    userName: record.userName || '',
    userAvatar: record.userAvatar || '',
    userProfile: record.userProfile || '',
    userRole: record.userRole || 'user',
  };
  editModalVisible.value = true;
};

// 重置编辑表单
const resetEditForm = () => {
  editForm.value = {
    id: 0,
    userName: '',
    userAvatar: '',
    userProfile: '',
    userRole: 'user',
  };
  editModalVisible.value = false;
};

// 处理编辑用户
const handleEdit = async () => {
  if (!editForm.value.userName) {
    message.error("请填写用户名");
    return;
  }

  try {
    const res = await UserControllerService.updateUserUsingPost(editForm.value);
    if (res.code === 0) {
      message.success("更新用户成功");
      editModalVisible.value = false;
      loadData();
      resetEditForm();
    } else {
      message.error("更新用户失败: " + res.message);
    }
  } catch (e) {
    message.error("更新用户失败");
    console.error(e);
  }
};

// 处理删除用户
const handleDelete = async (record: User) => {
  if (!confirm(`确定要删除用户 ${record.userName} 吗？`)) {
    return;
  }

  try {
    const res = await UserControllerService.deleteUserUsingPost({
      id: record.id,
    } as DeleteRequest);
    if (res.code === 0) {
      message.success("删除用户成功");
      loadData();
    } else {
      message.error("删除用户失败: " + res.message);
    }
  } catch (e) {
    message.error("删除用户失败");
    console.error(e);
  }
};

// 处理封禁用户
const handleBanUser = async (record: User) => {
  if (!confirm(`确定要封禁用户 ${record.userName} 吗？`)) {
    return;
  }

  try {
    const res = await UserControllerService.updateUserUsingPost({
      id: record.id,
      userRole: 'ban',
    } as UserUpdateRequest);
    if (res.code === 0) {
      message.success("封禁用户成功");
      loadData();
    } else {
      message.error("封禁用户失败: " + res.message);
    }
  } catch (e) {
    message.error("封禁用户失败");
    console.error(e);
  }
};

// 处理解封用户
const handleUnbanUser = async (record: User) => {
  try {
    const res = await UserControllerService.updateUserUsingPost({
      id: record.id,
      userRole: 'user',
    } as UserUpdateRequest);
    if (res.code === 0) {
      message.success("解封用户成功");
      loadData();
    } else {
      message.error("解封用户失败: " + res.message);
    }
  } catch (e) {
    message.error("解封用户失败");
    console.error(e);
  }
};
</script>

<style scoped>
/* 基础样式 */
.user-management-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  color: #333;
}

/* 搜索区域样式 */
.search-section {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.search-header h2 {
  margin: 0;
  color: #333;
  font-size: 1.5rem;
}

.search-filters {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: flex-end;
}

.filter-group {
  display: flex;
  flex-direction: column;
  min-width: 200px;
}

.filter-group label {
  margin-bottom: 8px;
  font-size: 0.9rem;
  color: #666;
}

.filter-input, .filter-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 0.9rem;
  transition: border-color 0.3s;
}

.filter-input:focus, .filter-select:focus {
  border-color: #409eff;
  outline: none;
}

/* 按钮样式 */
.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.3s;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.btn i {
  font-size: 0.9rem;
}

.btn-primary {
  background-color: #409eff;
  color: white;
}

.btn-primary:hover {
  background-color: #66b1ff;
}

.btn-search {
  background-color: #67c23a;
  color: white;
}

.btn-search:hover {
  background-color: #85ce61;
}

.btn-cancel {
  background-color: #f4f4f5;
  color: #909399;
}

.btn-cancel:hover {
  background-color: #e9e9eb;
}

.btn-confirm {
  background-color: #409eff;
  color: white;
}

.btn-confirm:hover {
  background-color: #66b1ff;
}

/* 表格样式 */
.user-table-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  overflow-x: auto;
}

.user-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 0.9rem;
}

.user-table th, .user-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.user-table th {
  background-color: #f8f8f9;
  color: #666;
  font-weight: 600;
}

.user-table tr:hover {
  background-color: #f5f7fa;
}

/* 用户头像样式 */
.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f0f2f5;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-fallback {
  font-weight: bold;
  color: #666;
}

/* 角色标签样式 */
.role-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: 500;
}

.role-user {
  background-color: #e6f7ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.role-admin {
  background-color: #fff2e8;
  color: #fa541c;
  border: 1px solid #ffbb96;
}

.role-ban {
  background-color: #f5f5f5;
  color: #8c8c8c;
  border: 1px solid #d9d9d9;
}

/* 用户简介样式 */
.user-profile {
  max-width: 200px;
}

.profile-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
}

.btn-action {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  cursor: pointer;
  transition: all 0.3s;
  color: white;
}

.btn-action i {
  font-size: 0.8rem;
}

.btn-edit {
  background-color: #409eff;
}

.btn-edit:hover {
  background-color: #66b1ff;
}

.btn-ban {
  background-color: #e6a23c;
}

.btn-ban:hover {
  background-color: #ebb563;
}

.btn-unban {
  background-color: #67c23a;
}

.btn-unban:hover {
  background-color: #85ce61;
}

.btn-delete {
  background-color: #f56c6c;
}

.btn-delete:hover {
  background-color: #f78989;
}

.btn-action:disabled {
  background-color: #c0c4cc;
  cursor: not-allowed;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  gap: 10px;
}

.pagination-btn {
  padding: 6px 12px;
  border: 1px solid #ddd;
  background-color: #fff;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.pagination-btn:hover:not(:disabled) {
  background-color: #f5f7fa;
  border-color: #c0c4cc;
}

.pagination-btn:disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}

.pagination-info {
  font-size: 0.9rem;
  color: #666;
}

.page-size-select {
  padding: 6px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-left: 15px;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-container {
  background-color: white;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  animation: modalFadeIn 0.3s;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 1.2rem;
  color: #333;
}

.modal-close {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #999;
  padding: 0;
}

.modal-close:hover {
  color: #666;
}

.modal-body {
  padding: 20px;
}

.modal-footer {
  padding: 15px 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 表单组样式 */
.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 0.9rem;
  color: #666;
}

.required {
  color: #f56c6c;
}

.form-input, .form-select, .form-textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 0.9rem;
  transition: border-color 0.3s;
}

.form-input:focus, .form-select:focus, .form-textarea:focus {
  border-color: #409eff;
  outline: none;
}

.form-textarea {
  resize: vertical;
  min-height: 60px;
}

.avatar-preview {
  margin-top: 10px;
  width: 60px;
  height: 60px;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #eee;
}

.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 图标样式 (使用Unicode字符或字体图标) */
.icon-add::before {
  content: "+";
}

.icon-search::before {
  content: "🔍";
}

.icon-edit::before {
  content: "✏️";
}

.icon-ban::before {
  content: "⛔";
}

.icon-unban::before {
  content: "✅";
}

.icon-delete::before {
  content: "🗑️";
}
</style>
